// routes/auth.js
import { Router } from "express";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";

const router = Router();
const JWT_SECRET = "your-secret-key-here"; // 建议从环境变量获取

// 注册接口
router.post("/register", async (req, res) => {
  const db = req.db;
  const { username, password } = req.body;

  // 验证输入
  if (!username || !password) {
    return res
      .status(400)
      .json({ error: "Username and password are required" });
  }

  // 检查用户名是否已存在
  const existingUser = db.data.users.find((user) => user.username === username);
  if (existingUser) {
    return res.status(409).json({ error: "Username already exists" });
  }

  try {
    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);

    // 创建新用户
    const newUser = {
      id: Date.now().toString(),
      username,
      password: hashedPassword,
      createdAt: new Date().toISOString(),
    };

    // 添加到数据库
    db.data.users.push(newUser);
    await db.write();

    // 返回成功响应（不包含密码）
    const userWithoutPassword = { ...newUser };
    delete userWithoutPassword.password;

    res.status(201).json({
      message: "User registered successfully",
      user: userWithoutPassword,
    });
  } catch (error) {
    console.error("Registration error:", error);
    res.status(500).json({ error: "Internal server error" });
  }
});

// 登录接口
router.post("/login", async (req, res) => {
  const db = req.db;
  const { username, password } = req.body;

  // 验证输入
  if (!username || !password) {
    return res
      .status(400)
      .json({ error: "Username and password are required" });
  }

  try {
    // 查找用户
    const user = db.data.users.find((user) => user.username === username);

    // 用户不存在
    if (!user) {
      return res.status(401).json({ error: "Invalid credentials" });
    }

    // 验证密码
    const isPasswordValid = await bcrypt.compare(password, user.password);
    if (!isPasswordValid) {
      return res.status(401).json({ error: "Invalid credentials" });
    }

    // 生成JWT令牌
    const token = jwt.sign(
      { userId: user.id, username: user.username },
      JWT_SECRET,
      { expiresIn: "1h" } // 令牌有效期
    );

    // 保存会话（可选）
    const session = {
      id: Date.now().toString(),
      userId: user.id,
      token,
      createdAt: new Date().toISOString(),
    };

    db.data.sessions.push(session);
    await db.write();

    // 返回成功响应
    res.json({
      message: "Login successful",
      token,
      user: {
        id: user.id,
        username: user.username,
        createdAt: user.createdAt,
      },
    });
  } catch (error) {
    console.error("Login error:", error);
    res.status(500).json({ error: "Internal server error" });
  }
});

// 登出接口
router.post("/logout", (req, res) => {
  // 注意：JWT无法主动失效，这里只是简单返回成功
  // 客户端应删除存储的令牌
  res.json({ message: "Logout successful" });
});

export default router;
